package com.shop.loan.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderBillByMybatisMapper;
import com.shop.loan.mapper.LoanOrderByMybatisMapper;
import com.shop.loan.mapper.LoanOrderPayLogByMybatisMapper;
import com.shop.loan.mapper.UserByMybatisMapper;
import com.shop.loan.model.entity.LoanOrderBillByMybatis;
import com.shop.loan.model.entity.LoanOrderByMybatis;
import com.shop.loan.model.entity.SettingByMybatis;
import com.shop.loan.model.enums.OpFailType;
import com.shop.loan.model.enums.OrderStatus;
import com.shop.loan.model.enums.PayType;
import com.shop.loan.model.vo.DiscountsVo;
import com.shop.loan.redis.RedisCache;
import com.shop.loan.util.LoanOrderUtil;
import com.shop.loan.util.OpFailUtil;
import com.shop.loan.util.PasswordUtil;
import com.shop.loan.util.Util;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.OperationHandler;
import xyz.erupt.upms.service.EruptUserService;
import xyz.erupt.upms.util.IpUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class DiscountsHandler implements OperationHandler<Object, DiscountsVo> {

    @Resource
    EruptUserService eruptUserService;

    @Resource
    OpFailUtil opFailUtil;

    @Resource
    HttpServletRequest request;

    @Resource
    LoanOrderUtil loanOrderUtil;

    @Resource
    LoanOrderBillByMybatisMapper loanOrderBillByMybatisMapper;

    @Resource
    LoanOrderByMybatisMapper loanOrderByMybatisMapper;

    @Resource
    UserByMybatisMapper userByMybatisMapper;

    @Resource
    RedisCache redisCache;

    @Resource
    LoanOrderPayLogByMybatisMapper loanOrderPayLogByMybatisMapper;

    @Transactional
    @Override
    public String exec(List<Object> data, DiscountsVo discountsVo, String[] param) {
        Object item = data.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
        Long id = jsonObject.getLongValue("id");

        /**
         * 校验还款密码
         */
        SettingByMybatis setting = redisCache.getSetting(false);
        if (!PasswordUtil.checkPassword(discountsVo.getPassword(), setting.getPayPassword())) {
            opFailUtil.opFailOp(IpUtil.getIpAddr(request), eruptUserService.getCurrentUid(), OpFailType.pay);
            return "msg.error('无效还款密码!')";
        }

        List<LoanOrderBillByMybatis> loanOrderBillByMybatisList = loanOrderBillByMybatisMapper.selectListByOrder(id);
        for (LoanOrderBillByMybatis loanOrderBillByMybatis : loanOrderBillByMybatisList) {
            if (loanOrderBillByMybatis.getPeriod() == discountsVo.getPeriod().intValue()) {
                LoanOrderBillByMybatis updateBill = new LoanOrderBillByMybatis();
                updateBill.setId(loanOrderBillByMybatis.getId());
                if (discountsVo.getPayType() == PayType.goods.getType().intValue()) {
//                    updateBill.setDiscountsMoneyByGoods(discountsVo.getNumber());
//                    loanOrderBillByMybatis.setDiscountsMoneyByGoods(discountsVo.getNumber());
                } else {
                    updateBill.setDiscountsMoney(discountsVo.getNumber());
                    loanOrderBillByMybatis.setDiscountsMoney(discountsVo.getNumber());
                }
                updateBill.setOverdueStatus(loanOrderBillByMybatis.getOverdueStatus());
                if (Util.checkIsSettle(loanOrderBillByMybatis)) {
                    //本金+利息 <= 优惠金额+还款金额  则结清
                    updateBill.setPayStatus(true);
                    updateBill.setOverdueStatus(true);
                } else {
                    updateBill.setPayStatus(false);
                }
                loanOrderBillByMybatisMapper.updateByPrimaryKeySelective(updateBill);

                loanOrderBillByMybatis.setPayStatus(updateBill.getPayStatus());
                if (updateBill.getOverdueStatus() != null) {
                    loanOrderBillByMybatis.setOverdueStatus(updateBill.getOverdueStatus());
                }
            }
        }
        LoanOrderByMybatis loanOrderByMybatis = new LoanOrderByMybatis();
        loanOrderByMybatis.setId(id);
        loanOrderByMybatis.setDiscountsMoney(loanOrderUtil.getBillDisMoney(loanOrderBillByMybatisList));
        loanOrderByMybatis.setPayMoney(loanOrderUtil.getBillPayMoney(loanOrderBillByMybatisList));
        loanOrderByMybatis.setOverdueStatus(loanOrderUtil.checkBillOverdue(loanOrderBillByMybatisList));
        if (loanOrderUtil.checkBillEnd(loanOrderBillByMybatisList)) {
            loanOrderByMybatis.setStatus(OrderStatus.end.getStatus());
            loanOrderByMybatis.setOverdueStatus(true);
            loanOrderByMybatis.setFinishTime(new Date());
            //订单结束 修改用户完结订单数
            userByMybatisMapper.updateUserEndNum(loanOrderByMybatis.getUserId());
        } else {
            loanOrderByMybatis.setStatus(OrderStatus.underway.getStatus());
        }
        loanOrderByMybatisMapper.updateByPrimaryKeySelective(loanOrderByMybatis);
        return null;
    }

    @Override
    public DiscountsVo eruptFormValue(List<Object> data, DiscountsVo discountsVo, String[] param) {
        Object item = data.get(0);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(item));
        Long id = jsonObject.getLongValue("id");

        LoanOrderByMybatis loanOrderByMybatis = loanOrderByMybatisMapper.selectByPrimaryKey(id);
        LoanOrderBillByMybatis loanOrderBillByMybatis = loanOrderBillByMybatisMapper.selectFirstUnPay(id);

        if (loanOrderByMybatis == null || loanOrderBillByMybatis == null) {
            return discountsVo;
        }
        BigDecimal periodPayMoney = loanOrderPayLogByMybatisMapper.selectSumByBillId(loanOrderBillByMybatis.getId(), null, PayType.principal_interest.getType());
        periodPayMoney = periodPayMoney == null ? BigDecimal.ZERO : periodPayMoney;
        BigDecimal periodGuaranteePayMoney = loanOrderPayLogByMybatisMapper.selectSumByBillId(loanOrderBillByMybatis.getId(), null, PayType.goods.getType());
        periodGuaranteePayMoney = periodGuaranteePayMoney == null ? BigDecimal.ZERO : periodGuaranteePayMoney;

        discountsVo.setTotalMoney(loanOrderByMybatis.getMoney().add(loanOrderByMybatis.getRateMoney()).add(loanOrderByMybatis.getShopMoney()));
        discountsVo.setPayMoney(loanOrderByMybatis.getPayMoney());
        discountsVo.setPeriod(loanOrderBillByMybatis.getPeriod());
        discountsVo.setTotalPeriod(loanOrderBillByMybatis.getTotalPeriod());
        discountsVo.setPeriodMoney(loanOrderBillByMybatis.getMoney());
        discountsVo.setPeriodRateMoney(loanOrderBillByMybatis.getRateMoney());
        discountsVo.setPeriodPayMoney(periodPayMoney);
        discountsVo.setPeriodDiscountMoney(loanOrderBillByMybatis.getDiscountsMoney() == null ? BigDecimal.ZERO : loanOrderBillByMybatis.getDiscountsMoney());
        loanOrderBillByMybatis.setPayMoney(periodPayMoney);
        discountsVo.setPeriodUnMoney(Util.getUnPayMoneyByPi(loanOrderBillByMybatis));
        discountsVo.setShopMoney(loanOrderByMybatis.getShopMoney());
        discountsVo.setPayMoneyByGoods(loanOrderByMybatis.getShopMoney());
        return discountsVo;
    }
}
